package xyz.mumuwei.youthcourseserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.mumuwei.youthcourseserver.common.dto.RouterDto;
import xyz.mumuwei.youthcourseserver.common.lang.Const;
import xyz.mumuwei.youthcourseserver.common.lang.Result;
import xyz.mumuwei.youthcourseserver.mapper.AuthorityMapper;
import xyz.mumuwei.youthcourseserver.mapper.RoleMapper;
import xyz.mumuwei.youthcourseserver.pojo.Authority;
import xyz.mumuwei.youthcourseserver.service.AuthorityService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author mumuwei
 * @since 2022-02-19
 */
@Slf4j
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, Authority> implements AuthorityService {

    private AuthorityMapper authorityMapper;
    private RoleMapper roleMapper;

    @Autowired
    public void setAuthorityMapper(AuthorityMapper authorityMapper) {
        this.authorityMapper = authorityMapper;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }


    /**
     * authIds 菜单 id 列表
     * @return 树状结构的菜单列表
     */
    @Override
    public Result getRoutes(List<Integer> authIds) {
        List<Authority> auths = authorityMapper.selectBatchIds(authIds);
        if (auths.size() == 0) {
            return Result.fail("当前账户无任何权限，请联系管理员！");
        }
        // 列表转树状结构
        List<Authority> authTree = buildTree(auths);
        return Result.success(authTree);
        // return Result.success(covertDto(authTree));
    }

    /**
     * 根据角色id获取权限列表
     *
     * @param roleId 角色id
     * @return 角色列表
     */
    @Override
    public Result getAuthListByRoleId(Integer roleId) {
        String idStr = roleMapper.selectById(roleId).getAuthorityId();
        if (!"".equals(idStr)) {
            String[] split = idStr.split(",");
            // 封装角色权限id
            ArrayList<Integer> authIds = new ArrayList<>();
            for (String r : split){
                authIds.add(Integer.parseInt(r));
            }
            // 获取权限列表
            List<Authority> authList = authorityMapper.selectBatchIds(authIds);
            List<Authority> authorityList = buildTree(authList);
            List<RouterDto> list = covertDto(authorityList);
            return Result.success(list);
        }
        return Result.success(new ArrayList<>());
    }


    /**
     * 将树状菜单列表转换为实际router实体
     *
     * @param menuTree 树状菜单列表
     * @return routerDto实体类树状列表
     */
    private List<RouterDto> covertDto(List<Authority> menuTree) {
        List<RouterDto> routerList = new ArrayList<>();
        menuTree.forEach(m -> {
            RouterDto dto = new RouterDto();

            dto.setId(m.getId());
            dto.setPath(m.getPath());
            dto.setComponent(m.getComponent());
            dto.setRedirect(m.getRedirect());
            dto.setName(m.getName());
            dto.setHidden(m.getHidden());
            dto.setAlwaysShow(m.getAlwaysShow());

            // 设置 meta
            HashMap<String, Object> meta = new HashMap<>(10);
            meta.put("title", m.getTitle());
            meta.put("icon", m.getIconName());
            meta.put("noCache", m.getNoCache());
            meta.put("breadcrumb", m.getBreadcrumb());
            meta.put("affix", m.getAffix());
            meta.put("activeMenu", m.getActiveMenu());
            dto.setMeta(meta);

            if (m.getChildren().size() > 0) {
                // 子节点调用当前方法进行再次转换
                dto.setChildren(covertDto(m.getChildren()));
            }

            routerList.add(dto);
        });
        return routerList;
    }

    /**
     * 获取树状结构的菜单列表
     *
     * @param menus 菜单列表
     * @return 树状菜单列表
     */
    private List<Authority> buildTree(List<Authority> menus) {
        List<Authority> parentList = authorityMapper.selectList(new QueryWrapper<Authority>().eq("parent_id", 10));
        List<Authority> finalMenus = new ArrayList<>();
        // 先各自寻找各自的孩子
        for (Authority menu : parentList) {
            for (Authority item : menus) {
                if (menu.getId().equals(item.getParentId())) {
                    menu.getChildren().add(item);
                }
            }
            if (menu.getParentId().equals(Const.TOP_AUTHORITY) && menu.getChildren().size() > 0) {
                finalMenus.add(menu);
            }
        }
        return finalMenus;
    }

}
